package org.netty.im.common;

import java.net.InetSocketAddress;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

@Component
public class StartRunner implements CommandLineRunner{
	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private ChatServer chatServer;
	
	@Override
	public void run(String... args) throws Exception {
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 6666);
		ChannelFuture future = chatServer.start(address);
		
		future.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                	logger.info("websocketserver have success bind to " + address.getPort());
                } else {
                	logger.error("websocketserver fail bind to " + address.getPort());
                }
            }
        });
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				chatServer.destroy();
			}
		});
		
		future.channel().closeFuture().syncUninterruptibly();
	}

}
